package com.aric.springbootmusic.handler;

import com.aric.springbootmusic.utils.Result;
import com.aric.springbootmusic.utils.ResultUtil;
import com.aric.springbootmusic.utils.WebUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

//处理认证阶段出现的认证异常
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException{
        authException.printStackTrace();
        Result result = ResultUtil.getResponseResult(HttpStatus.UNAUTHORIZED.value(), "用户认证失败，请重新登陆", null);
        ObjectMapper objectMapper=new ObjectMapper();
        //将对象转换为json字符串
        String s = objectMapper.writeValueAsString(result);
        //处理异常
        WebUtils.renderString(response,s);
    }
}
